<template>
  <el-upload
    class="upload"
    action="/api/file/upload"
    :headers="headers"
    :on-success="handleSuccess"
    :on-error="handleError"
    :on-remove="handleRemove"
    :file-list="fileList"
    v-bind="$attrs"
    v-on="$listeners"
  >
    <slot></slot>
  </el-upload>
</template>

<script>
import { getToken } from 'app/global'
export default {
  name: 'Upload',
  model: {
    prop: 'fileList',
    event: 'change'
  },
  props: {
    fileList: {
      type: Array,
      default: () => []
    },
    single: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      headers: { Authorization: getToken() }
    }
  },
  methods: {
    handleSuccess(response) {
      const file = response.data
      this.$emit('upload', response.data)
      const arr = this.single ? [file] : [...this.fileList, file]
      this.$emit('change', arr)
    },
    handleError(err) {
      const { message } = JSON.parse(err.message)
      message && this.$error(message)
    },
    handleRemove(file) {
      const arr = this.fileList.filter(item => item !== file)
      this.$emit('change', arr)
    }
  }
}
</script>

<style lang="scss">
@import 'styles/common.scss';
.upload {
  display: inline-block;
}
</style>
